<template>
  <div class="good_content">
    <loading-app v-if="showLoading"></loading-app>
    <div class="good" :class="{'goods_top2':menu_wrapper_status === 0,'goods_top0':menu_wrapper_status === 1}" v-if="!showLoading">
      <div class="menu-wrapper" ref="menuWrapper">
        <ul>
          <li v-for="(item, index) in publicList" class="menu-item border-1px" :class="{'current':currentIndex === index}"
              @click="selectMenu(index, $event)">
            <span class="text">
              <span v-show="item.type>0" class=" icon" :class="classMap[item.id]"></span>
              {{item.title}}
            </span>
          </li>
        </ul>
      </div>
      <div class="foods-wrapper" ref="foodWrapper">
        <ul>
          <li v-for="item in publicList" class="food-list food-list-hook">
            <h1 class="title">{{item.title}}</h1>
            <ul>
              <li v-for="food in item.shop_goods" class="food-item" @click="selectFood(food, $event)">
                <div class="icon">
                  <img :src="food.goods_img" alt="" width="57">
                </div>
                <div class="content">
                  <span class="name">{{food.goods_name}}</span>
                  <!--<p class="desc">{{food.description}}</p>-->
                  <div class="extra">
                    <span class="count">月售{{food.sale_num}}</span><!--<span class="count">好评{{food.rating}}</span>-->
                  </div>
                  <div class="price">
                    <span class="now">￥{{food.goods_price}}</span><span class="old"
                                                                  v-show="food.oldPrice">￥{{food.oldPrice}}</span>
                  </div>
                  <div class="cartControl-wrapper">
                    <div class="cartControl">
                      <transition name="fade">
                        <div class="cart-decrease" @click.stop.prevent="decreaseCart(food,$event)" v-show="food.count > 0">
                          <transition name="inner">
                            <span class="inner iconfont icon-jian">
                              <img src="../img/minus-circle.png">
                            </span>
                          </transition>
                        </div>
                      </transition>
                      <span class="cart-count" v-show="food.count > 0">
                           {{food.count}}
                        </span>
                      <span class="iconfont icon-jia cart-add" @click.stop.prevent="addCart(food,$event)" :id="'cart-add'+ food.id" >
                        <img src="../img/add.png">
                      </span>
                    </div>
                    <!--<cartControl :food="food" :item_cart_list="item_cart_list" cart_list_ids="cart_list_ids" :item_cart_num="item_cart_num" v-on:childByValue="childByValue"></cartControl>  &lt;!&ndash;@increment="incrementTotal"&ndash;&gt;-->
                  </div>
                </div>
              </li>
            </ul>
          </li>
        </ul>
        <loadingApp v-if="loading_status"></loadingApp>
      </div>
      <div>
        <shopCart :select-foods="selectFoods" ref="shopCart"></shopCart>
        <!--<food :food="selectedFood" ref="food"></food>-->
      </div>
      <div class="cartShopProduct" @click="toJiesun">
        <p class="jiesuan">
          <img class="jiesuan_cart" src="../img/cart3.png">
          <span>{{item_cart_num}}</span>
        </p>
        <!--<router-link :to="'/qds/buildOrder'">-->
          <p class="button" >去结算</p>
        <!--</router-link>-->
      </div>
      <div class="ball-container"><!--小球-->
        <div v-for="ball in balls">
          <transition name="drop" @before-enter="beforeDrop" @enter="dropping" @after-enter="afterDrop">
            <div class="ball" v-show="ball.show">
              <div class="add_cart inner-hook"></div>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
  import Vue from 'vue';
  import BScroll from 'better-scroll';
  import shopCart from '../components/shopCart.vue';
  import cartControl from '../components/cartControl.vue';

  import loadingApp from '../../loading';
  export default {
    props: {
      seller: {
        type: Object
      },
    },
    data () {
      return {
        showLoading:true,
        goods: [],
        listHeight: [],
        scrolly: 0,
        selectedFood: {},
        menu_wrapper_status:null,
        publicList:'',
        item_cart_list: [],//JSON.parse(localStorage.getItem('itemCartList')) || [], //已经选取的购物车的商品
        cart_list_ids:'',
        item_cart_num:0,
        dropBalls:[],
        balls: [ //小球 设为3个
          {
            show: false
          },
          {
            show: false
          },
          {
            show: false
          },
        ],
        loading_status:true,
        scrolly_top:0
      };
    },
    mounted(){
      this.checkLogin();
      this.item_cart_list = JSON.parse(this.getCache(this.getKey('itemCartList'))) ||[];
      console.log(this.item_cart_list)
      this.initList();
    },
    created() {

    },
    computed: {
      currentIndex(val,oldval) {
        if(this.scrolly_top === 0 || this.scrolly_top === 8){
           this.menu_wrapper_status = 0;
           $('.tab_choose').removeClass('tab_change_pos');
        }else {
          this.menu_wrapper_status = 1;
          $('.tab_choose').addClass('tab_change_pos');
        }


       /* this.$emit('childByValue', this.menu_wrapper_status)*/
        for (let i = 0; i < this.listHeight.length; i++) {
          let height = this.listHeight[i];
          let height2 = this.listHeight[i + 1];
          if (!height2 || (this.scrolly >= height && this.scrolly < height2)) {
            return i;
          }
        }
        return 0;
      },
      selectFoods() {
        let foods = [];
        if(this.publicList != undefined && this.publicList != null && this.publicList!= '' && this.publicList.length >0){
          this.publicList.forEach((good) => {
            good.shop_goods.forEach((product) => {
              if (product.count) {
                foods.push(product);
              }
            });
          });
        }
        return foods;
      }
    },
    methods: {
      initList(){
        this.yesS.getGoodsList(
          this.$comParams()
        ).then((res) => {
          var obj = res.data;
          if(this.isEmpty(obj) || this.isEmpty(obj.goods_list)){
            this.$toast.warning('暂无数据');
            return;
          }
          this.publicList = res.data.goods_list;
          console.log(this.publicList)
          this.publicList.forEach((obj) => {
            obj.shop_goods.forEach((obj1) => {
              obj1.count = 0;
              if(this.item_cart_list.length >0){
                this.item_cart_list.forEach((cart) => {
                  if(cart.id == obj1.id){
                    obj1.count = cart.count;
                    this.cart_list_ids +=','+obj1.id;
                  }
                })
              }
              this.item_cart_num += obj1.count;
            });
          });
          this.showLoading = false;
          this.$emit('childByValue', this.showLoading)
          this.$nextTick(() => {
            this._initScroll();
            this._calculateHeight();
          });
        })

        this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee'];
      },
      _initScroll() {
        this.menuScroll = new BScroll(this.$refs.menuWrapper, {
          click: true
        });
        this.foodScroll = new BScroll(this.$refs.foodWrapper, {
          probeType: 3,
          click: true
        });
        this.foodScroll.on('scroll', (pos) => {
          this.scrolly = Math.abs(Math.round(pos.y));
        });
        this.foodScroll.on('scrollEnd',(pos) => {
          this.scrolly_top = Math.abs(Math.round(pos.y));
        })
      },
      _calculateHeight() {
        let foodList = this.$refs.foodWrapper.getElementsByClassName('food-list-hook');
        foodList = document.getElementsByClassName('food-list-hook')
        let height = 0;
        this.listHeight.push(height);
        for (let i = 0; i < foodList.length; i++) {
          let item = foodList[i];
          height += item.clientHeight;
          this.listHeight.push(height);
        }
      },

      selectMenu(index, event) {
        if (!event._constructed) {
          // 去掉自带click事件的点击
          return;
        }
        let foodList = this.$refs.foodWrapper.getElementsByClassName('food-list-hook');
        let el = foodList[index];
        this.foodScroll.scrollToElement(el, 300);
      },
      selectFood(food, event) {

      },

      addCart(food,event) {
        this.drop(event.target);
        this.item_cart_num =  this.item_cart_num + 1;
        if (!food.count) {
          Vue.set(food, 'count', 1);
        } else {
          food.count++;
        }
        if(this.item_cart_list.length >0){
          for (var i in this.item_cart_list) {
            var obj = this.item_cart_list[i];
            if (this.cart_list_ids.indexOf(','+food.id) != -1 && obj.id === food.id) {
              obj.count = food.count;
              break;
            } else if(this.cart_list_ids.indexOf(','+food.id) == -1) {
              this.cart_list_ids+=','+food.id;
              this.item_cart_list.push(food);
            }
          }
        }else {
          this.cart_list_ids+=','+food.id;
          this.item_cart_list.push(food)
        }
      },
      drop(el){ //抛物
        for(let i=0;i<this.balls.length;i++){
          let ball= this.balls[i];
          if(!ball.show){
            ball.show = true;
            ball.el=el;
            this.dropBalls.push(ball);
            return;
          }
        }
      },
      beforeDrop(el) {/* 购物车小球动画实现 */
        let count = this.balls.length;
        while (count--) {
          let ball = this.balls[count];
          if (ball.show) {
            let rect = ball.el.getBoundingClientRect(); //元素相对于视口的位置
            let x = rect.left - 32;
            let y = -(window.innerHeight - rect.top - 22);  //获取y
            el.style.display = '';
            el.style.webkitTransform = 'translateY('+y+'px)';  //translateY
            el.style.transform = 'translateY('+y+'px)';
            let inner = el.getElementsByClassName('inner-hook')[0];
            inner.style.webkitTransform = 'translateX('+x+'px)';
            inner.style.transform = 'translateX('+x+'px)';
          }
        }
      },
      dropping(el, done) { /*重置小球数量  样式重置*/
        let rf = el.offsetHeight;
        el.style.webkitTransform = 'translate3d(0,0,0)';
        el.style.transform = 'translate3d(0,0,0)';
        let inner = el.getElementsByClassName('inner-hook')[0];
        inner.style.webkitTransform = 'translate3d(0,0,0)';
        inner.style.transform = 'translate3d(0,0,0)';
        el.addEventListener('transitionend', done);
      },
      afterDrop(el) { /*初始化小球*/
        let ball = this.dropBalls.shift();
        if (ball) {
          ball.show=false;
          el.style.display = 'none';
        }
      },
      decreaseCart(food,event) {
        this.item_cart_num =  this.item_cart_num - 1;
        food.count--;

        if(this.item_cart_list.length >0){
          for (var i in this.item_cart_list) {
            var obj = this.item_cart_list[i];
            if (this.cart_list_ids.indexOf(food.id) != -1 && obj.id === food.id) {
              obj.count = food.count;
              if(food.count < 1){
                this.item_cart_list.splice(i, 1);
                this.cart_list_ids.replace(','+food.id,'');
              }
            }
          }
        }
      },

      toJiesun(){
        if(this.isEmpty(this.item_cart_num) || parseInt(this.item_cart_num) <=0){
          this.$toast.warning('请选择商品');
          return;
        }
        this.$router.push({path:'/qds/buildOrder'})

      }
    },
    watch:{
      item_cart_num:{
        handler(curVal,oldVal){
          if(this.item_cart_list.length > 0){
            for(var i=0;i<this.item_cart_list.length;i++){
              this.item_cart_list[i].choose_waterBill = true;
              this.item_cart_list[i].setAllMoney = 1;//表示结算时需要算价钱
            }
          }
          console.log(this.item_cart_list)
          this.setCache(this.getKey('itemCartList'), JSON.stringify(this.item_cart_list));
        },
        deep:true
      },
    },
    components: {
      shopCart,
     /* cartControl,*/
      /*food*/
      loadingApp
    }
  };
</script>
<style lang="stylus" rel="stylesheet/stylus">
  @import "../css/content_mint.css";
  @import "../css/cartControl.css"
  /*@import 'http://cdn.bootcss.com/material-design-icons/3.0.1/iconfont/material-icons.css';*/
</style>
